package client;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class Main extends BaseFrame {

	private static final long serialVersionUID = -6713879855817534631L;

	private static int height = 400;
	private static int width = 400;
	private PriorityMessageQueue messageQueue;

	/**
	 * Main entry point.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		// Main game = new Main();
		new Main().run();
		// game.run();
	}

	public Main() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//this.setUndecorated(true);
		//this.setSize(width, height);
		this.setVisible(true);
		this.setResizable(false);
		//Without canvas, frame width and height messes up.
		Canvas canvas = new Canvas();
		canvas.setIgnoreRepaint(true);
		canvas.setSize(width, height);
		canvas.setFocusable(false); 
		this.add(canvas);
		this.pack();
		canvas.createBufferStrategy(2);
		bf = canvas.getBufferStrategy();
		messageQueue = new PriorityMessageQueue();
		super.start();
	}

	/**
	 * What state the game is in.
	 */
	private StateContext stateContext;
	/**
	 * Keeps track of how many frames have passed since starting the game.
	 */
	private int GameTime = 0;
	BufferStrategy bf;

	public void drawWorld() {

		Graphics g = null;
		do {
			do {
				g = bf.getDrawGraphics();
				setBackground(Color.BLACK);
				stateContext.paint(g, GameTime);
				stateContext.processKeyHit(_kb);
				messageQueue.paint(g, GameTime);
				GameTime++;
				g.dispose();
			} while (bf.contentsRestored());

			// Shows the contents of the backbuffer on the screen.
			bf.show();
		} while (bf.contentsLost());
		
		// ensures that the screen is up to date with any events
		Toolkit.getDefaultToolkit().sync();
	}

	@Override
	public void run() {
		// createImageAndGraphics();
		stateContext = new StateContext();
		requestFocusInWindow(); // doesn't start with focus
		while (_gameRunning) {

			drawWorld();
			showAndWait();
		}
	}

	@Override
	public String getName() {
		return "MTG: Search for the Black Lotus";
	}

	@Override
	public int getHeight() {
		return height;
	}

	@Override
	public int getWidth() {
		return width;
	}

	public static int staticHeight() {
		return height;
	}

	public static int staticWidth() {
		return width;
	}
}
